/*
 * @lc app=leetcode.cn id=19 lang=javascript
 *
 * [19] 删除链表的倒数第 N 个结点
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
var removeNthFromEnd = function (head, n) {
  return removeNode(head, n) === n ? head.next : head
  // let leftFast = 0  // 指向当前第n个元素
  // let leftLow = 0 // 指向当前第n个元素
  // let headFast = head
  // let headLow
  // while (headFast != null) {
  //   leftFast++
  //   if (leftFast > n) {
  //     leftLow++
  //     headLow = leftLow === 1 ? head : headLow.next
  //   }
  //   headFast = headFast.next
  // }
  // if (leftLow === 0) {
  //   head = head.next
  // } else {
  //   headLow.next = headLow.next.next
  // }
  // return head
}
function removeNode(node, n) {
  if (node.next === null) return 1
  let m = removeNode(node.next, n)
  if (m === n) {
    if (m === 1) node.next = null
    else node.next = node.next.next
  }
  return m + 1
}
// @lc code=end

